/*
package com.top.util;

*/
/**
 * @Autor zhangjiawen
 * @Date: 2020/8/8 17:12
 *//*




iimport java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import com.schj.entity.ExcelColumn;

*/
/**
 * @author ABT
 * @description
 **//*

public class ExcelUtil {

    private final static Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";

    public static <T> List<T> readExcel(String path, Class<T> cls,
                                        MultipartFile file) throws Exception {

        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$")
                && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            log.error("上传文件格式不正确");
        }
        List<T> dataList = new ArrayList<>();
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.endsWith(EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            if (workbook != null) {
                // 类映射 注解 value-->bean columns
                Map<String, List<Field>> classMap = new HashMap<>();
                List<Field> fields = Stream.of(cls.getDeclaredFields())
                        .collect(Collectors.toList());
                fields.forEach(field -> {
                    ExcelColumn annotation = field
                            .getAnnotation(ExcelColumn.class);
                    if (annotation != null) {
                        String value = annotation.value();
                        if (StringUtils.isBlank(value)) {
                            return;// return起到的作用和continue是相同的 语法
                        }
                        if (!classMap.containsKey(value)) {
                            classMap.put(value, new ArrayList<>());
                        }
                        field.setAccessible(true);
                        classMap.get(value).add(field);
                    }
                });
                // 索引-->columns
                Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);
                // 默认读取第一个sheet
                Sheet sheet = workbook.getSheetAt(0);

                boolean firstRow = true;
                for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    // 首行 提取注解
                    if (firstRow) {
                        for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                            Cell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            if (classMap.containsKey(cellValue)) {
                                reflectionMap.put(j, classMap.get(cellValue));
                            }
                        }
                        firstRow = false;
                    } else {
                        // 忽略空白行
                        if (row == null) {
                            continue;
                        }
                        try {
                            T t = cls.newInstance();
                            // 判断是否为空白行
                            boolean allBlank = true;
                            for (int j = row.getFirstCellNum(); j <= row
                                    .getLastCellNum(); j++) {
                                if (reflectionMap.containsKey(j)) {
                                    Cell cell = row.getCell(j);
                                    String cellValue = getCellValue(cell);
                                    if (StringUtils.isNotBlank(cellValue)) {
                                        allBlank = false;
                                    }
                                    List<Field> fieldList = reflectionMap.get(j);
                                    fieldList.forEach(x -> {
                                        try {
                                            handleField(t, cellValue, x);
                                        } catch (Exception e) {
                                            log.error(
                                                    String.format(
                                                            "reflect field:%s value:%s exception!",
                                                            x.getName(),
                                                            cellValue),
                                                    e);
                                        }
                                    });
                                }
                            }
                            if (!allBlank) {
                                dataList.add(t);
                            } else {
                                log.warn(String.format(
                                        "row:%s is blank ignore!", i));
                            }
                        } catch (Exception e) {
                            log.error(
                                    String.format("parse row:%s exception!", i),
                                    e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(String.format("parse excel exception!"), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    log.error(String.format("parse excel exception!"), e);
                }
            }
        }
        return dataList;
    }

    private static <T> void handleField(T t, String value, Field field)
            throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);
            // 数字类型
        } else if (type.getSuperclass() == null
                || type.getSuperclass() == Number.class) {
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(StringUtils.substringBefore(
                        value, ".0")));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.class || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            field.set(t, value);
        } else if (type == String.class) {
            if (value.endsWith(".0")) {
                value = StringUtils.substringBefore(value, ".0");
            }
            if (value.endsWith(" 00:00:00")) {
                value = StringUtils.substringBefore(value, " 00:00:00");
            }
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                short format = cell.getCellStyle().getDataFormat();
                System.out.println("format:" + format + ";;;;;value:" + cell.getNumericCellValue());
                SimpleDateFormat sdf = null;
                if (format == 14 || format == 31 || format == 57
                        || format == 58 || (176 <= format && format <= 178)
                        || (182 <= format && format <= 196)
                        || (210 <= format && format <= 213) || (208 == format)) { // 日期
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                } else if (format == 20 || format == 32 || format == 183
                        || (200 <= format && format <= 209)) { // 时间
                    sdf = new SimpleDateFormat("HH:mm");
                } else { // 不是日期格式
                    return String.valueOf(cell.getNumericCellValue());
                }
                double value = cell.getNumericCellValue();
                Date date = org.apache.poi.ss.usermodel.DateUtil
                        .getJavaDate(value);
                if (date == null || "".equals(date)) {
                    return "";
                }
                String result = "";
                try {
                    result = sdf.format(date);
                } catch (Exception e) {
                    e.printStackTrace();
                    return "";
                }
                return result;

            } */
/*else if (String.valueOf(cell.getNumericCellValue()).indexOf("E") == -1) {
                return String.valueOf(cell.getNumericCellValue());
            } *//*
else {
                */
/*return new DecimalFormat("#")
                        .format(cell.getNumericCellValue());*//*

                return String.valueOf(cell.getNumericCellValue());
            }
            */
/*
             * // 日期处理(目前不能处理包含中文的日期类型) if
             * (HSSFDateUtil.isCellDateFormatted(cell)) { return
             * HSSFDateUtil.getJavaDate(cell.getNumericCellValue()) .toString();
             * } else { return new
             * BigDecimal(cell.getNumericCellValue()).toString(); }
             *//*

        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            if (cell.getStringCellValue().contains("年") && cell.getStringCellValue().contains("月")&& cell.getStringCellValue().contains("日")) {
                return DateUtil.parseDateToString(DateUtil.parseStringToDate(
                        cell.getStringCellValue(), "yyyy年MM月dd日HH:mm:ss"),
                        "yyyy-MM-dd");
            } else if (StringUtil.count(cell.getStringCellValue(), "-") >= 2) {
                return DateUtil.parseDateToString(DateUtil.parseStringToDate(
                        cell.getStringCellValue(), "yyyy-MM-dd"), "yyyy-MM-dd");
            }
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }

    */
/**
     * 浏览器下载excel
     *
     * @param fileName
     * @param wb
     * @param response
     *//*


    private static void buildExcelDocument(String fileName, Workbook wb,
                                           HttpServletResponse response) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "utf-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    */
/**
     * 生成excel文件
     *
     * @param path
     *            生成excel路径
     * @param wb
     *//*

    @SuppressWarnings("unused")
    private static void buildExcelFile(String path, Workbook wb) {

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            wb.write(new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    */
/**
     * 渠道结算导入模板
     * <p>
     * Title: writeUAccountExcel
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param response
     *//*

    public static <T> void writeUAccountExcel(HttpServletResponse response) {

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("Sheet1");
        // 写入表头
        XSSFRow row = sheet.createRow(0);
        // 设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 20 * 256);
        sheet.setColumnWidth(2, 10 * 256);
        sheet.setColumnWidth(3, 20 * 256);
        sheet.setColumnWidth(4, 10 * 256);

        CreationHelper createHelper = wb.getCreationHelper();

        XSSFFont xssfFont = wb.createFont();
        xssfFont.setColor(org.apache.poi.ss.usermodel.Font.COLOR_RED);

        CellStyle redFontStyle = wb.createCellStyle();
        redFontStyle.setFont(xssfFont);

        CellStyle DateStyle = wb.createCellStyle();
        DateStyle.setFont(xssfFont);
        DateStyle.setDataFormat(createHelper.createDataFormat().getFormat(
                "yyyy-MM-dd"));


        XSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("保单号");
        cell.setCellStyle(redFontStyle);

        cell = row.createCell(1);
        cell.setCellValue("险种代码");
        cell.setCellStyle(redFontStyle);

        cell = row.createCell(2);
        cell.setCellValue("缴费期次");
        cell.setCellStyle(redFontStyle);

        cell = row.createCell(3);
        cell.setCellValue("供应商编码");
        cell.setCellStyle(redFontStyle);

        cell = row.createCell(4);
        cell.setCellValue("结算日期");
        cell.setCellStyle(redFontStyle);

        // 冻结窗格
        wb.getSheet("Sheet1").createFreezePane(0, 1, 0, 1);
        // 浏览器下载excel
        buildExcelDocument("上游结算导入.xlsx", wb, response);
        // 生成excel文件
        // buildExcelFile("供应商费率导入.xlsx",wb);
    }
}
*/
